<template>
  <div>
    <!-- 城市下拉选框 -->
    <van-field
      class="zdy_field"
      v-model="fieldValue"
      is-link
      readonly
      label=""
      placeholder=""
      @click="show = true"
    />
    <van-popup v-model="show" round position="bottom">
      <van-cascader
        v-model="cascaderValue"
        title="请选择所在地区"
        :options="options"
        @close="show = false"
        @finish="onFinish"
        @change="cityChange"
      />
    </van-popup>
  </div>
</template>

<script>
export default {
  data() {
    return {
      show: false,
      fieldValue: "",
      fieldId: [],
      cascaderValue: "",
      // 选项列表，children 代表子选项，支持多级嵌套
      options: [],
      // 传入的数据格式
      // {
      //   text: "浙江省",
      //   value: "330000",
      //   children: [{ text: "杭州市", value: "330100" }],
      // }
    };
  },
  mounted() {
    this.getProvinceData();
  },
  methods: {
    // 全部选项选择完毕后，会触发 finish 事件
    onFinish({ selectedOptions }) {
      this.show = false;
      this.fieldValue = selectedOptions.map(option => option.text).join("/");
      this.fieldId = selectedOptions.map(option => option.value);
      this.$router.push({
        name: "addrlist",
        params: { provinceId: this.fieldId[0], cityId: this.fieldId[1] },
      });
    },
    getProvinceData() {
      // 获取省的数据
      this.axios.get("map/province").then(res => {
        // console.log(res);
        res.data.data.forEach(item => {
          let x = {
            text: item.province,
            value: item.provinceId,
            children: [],
          };
          this.options.push(x);
          // { text: item.city, value: item.cityId }
        });
      });
    },
    getCityData(value) {
      // 获取市的数据
      this.options.some((item, index) => {
        if (value == item.value) {
          // 获取市的数据
          let params = `provinceId=${value}`;
          this.axios.post("map/city", params).then(res => {
            this.options[index].children = [];
            res.data.data.forEach(item => {
              let x = { text: item.city, value: item.cityId };
              this.options[index].children.push(x);
            });
          });
        }
      });
    },
    // change时触发
    cityChange({ value }) {
      this.getCityData(value);
    },
  },
};
</script>

<style lang="scss">
.zdy_field {
  &.van-field {
    width: 50px;
  }
  background: url("/src/assets/mapicon/add_location.png") no-repeat;
  background-size: 50%;
  background-position: center;
  .van-icon-arrow:before {
    content: "";
  }
  .van-icon:before {
    display: none;
  }
  .van-field__control {
    visibility: hidden;
  }
}
.zdy_field.van-cell{
  background-color: #36c14c;
}
</style>
